package cn.edu.ctbu.dp01.service;

import cn.edu.ctbu.dp01.constant.REnum;
import cn.edu.ctbu.dp01.dao.StudentRepository;
import cn.edu.ctbu.dp01.entity.Student;
import cn.edu.ctbu.dp01.exception.RException;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;


import java.util.List;

@Service
public class StudentService {

    @Autowired
    public StudentRepository studentRepository;

    /*
     *  都所有学生列表
     *  @return List<Student>
     */
    public List<Student> getAll(){

        return studentRepository.findAll();
    }



    public Page<Student> getAll(Pageable pageable) {

        return studentRepository.findAll(pageable);
    }

    public Page<Student> getAll(Example<Student> example, Pageable pageable){

        return studentRepository.findAll(example, pageable);
    }

    /*
     * 按id进行查询
     * @param id主键 整数
     * */
    public Student findById(Integer id){


        return studentRepository.findById(id).orElse(null);
    }

    /*
     * 按name进行查询
     * @param name 字符型
     * */
    public List<Student> findByNameLike(String name){


        return studentRepository.findByNameLike(name);
    }

    /**
     * 按名字和密码进行查询
     * @param name
     * @param password
     * @return
     */
    public List<Student> findByNameAndPassword(String name, String password){


        return studentRepository.findByNameAndPassword(name, password);
    }

    //CRUD(create read update delete)

    public Student add(Student student){

        return studentRepository.save(student);
    }

    public Student update(Student student){

        return studentRepository.save(student);
    }

    public void delete(Integer id){

        studentRepository.deleteById(id);
    }

    public List<Student> inquire(String name){

        return studentRepository.findByName(name);
    }


    public Student validateSnoAndPassword(String sno, String password) throws Exception{

        List<Student> students = studentRepository.findBySno(sno);
        if(!students.isEmpty()){
            //可能对Password加密， 但我们暂时不能处理
            Student student = students.get(0);
            if(student.getPassword().equals(password)){

                return student;
            }
            else
                throw new RException(REnum.LOGIN_ERR);

        }else
            throw new RException(REnum.LOGIN_ERR);
    }



}
